<template>
  <div class="CarModelSearchWrap table-page-search-wrapper">
    <div class="listSearchWrap table-page-search-wrapper">
      <a-row :gutter="[8, 16]">
        <a-col v-show="false"
          :xs="12"
          :sm="12"
          :md="12"
          :lg="7"
          :xl="5"
          :xxl="5">
          <a-select
            style="width:100%"
            allow-clear
            mode="multiple"
            :maxTagCount="1"
            v-model="queryParams.upgradeStatus"
            :placeholder="$t('pleaseSelect')+$t('czzt').toLowerCase()">
            <a-select-option
              v-for="(item,indexer) in operationStatus"
              :key="indexer"
              :value="item.id"
              :title="$t(item.name)"

            >
              {{ $t(item.name) }}
            </a-select-option>
          </a-select>
        </a-col>
        <a-col
          :xs="12"
          :sm="12"
          :md="6"
          :lg="7"
          :xl="5"
          :xxl="5">
          <a-select
            style="width:100%"
            mode="multiple"
            :maxTagCount="1"
            v-model="queryParams.status"
            :placeholder="$t('pleaseSelect')+$t('sbzt').toLowerCase()"
            allow-clear>
            <a-select-option
              v-for="(item,indexer) in taskVehicleStatusOptions"
              :key="indexer"
              :value="item.value"
              :title="item.name"
            >
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-col>
        <a-col
          :xs="12"
          :sm="12"
          :md="12"
          :lg="10"
          :xl="14"
          :xxl="14">
          <filter-box-collection
            filterBoxCls="detailTaskFilterBoxCol"
            :queryParam="queryParamsDesc"
            class="detailTaskFilterBoxCol"
            @removetag="removeQueryKey"
            @search="handleSearch"
          >
            <template slot>
              <!-- vin -->
              <a-row :gutter="20">
                <a-col :md="24" :sm="24">
                  <a-form-model-item label="VIN" prop="vin" >
                    <a-input v-model="queryParams.vin" :placeholder="$t('pleaseSelect')+'VIN'" @change="inputVin"/>
                  </a-form-model-item>
                </a-col>
              </a-row>
              <a-row :gutter="20">
                <a-col :md="24" :sm="24">
                  <a-form-model-item label="导入车辆批次号" prop="importBatch" >
                    <a-input v-model="queryParams.importBatch" :placeholder="$t('pleaseSelect')+'导入车辆批次号'" @change="inputImportBatch"/>
                  </a-form-model-item>
                </a-col>
              </a-row>
              <!-- 开始时间 -->
              <a-row>
                <a-col :md="24" :sm="24">
                  <a-form-model-item :label="$t('startTime')" class="productionYearRow">
                    <a-range-picker
                      format="YYYY-MM-DD"
                      :placeholder="[$t('startTime'), $t('endTime')]"
                      :value="defaultStartTime"
                      @change="selectStartTime"
                    />
                  </a-form-model-item>
                </a-col>
              </a-row>
              <!-- 状态更新时间 -->
              <a-row>
                <a-col :md="24" :sm="24">
                  <a-form-model-item :label="$t('ztgsTime')" class="productionYearRow">
                    <a-range-picker
                      format="YYYY-MM-DD"
                      :placeholder="[$t('startTime'), $t('endTime')]"
                      :value="defaultUpdateTime"
                      @change="selectUpdateTime"
                    />
                  </a-form-model-item>
                </a-col>
              </a-row>
              <!-- 预约时间 -->
              <a-row v-if=" type === 2 ">
                <a-col :md="24" :sm="24">
                  <a-form-model-item label="预约时间" class="productionYearRow">
                    <a-range-picker
                      style="width: 100%;"
                      :show-time="{
                        format:'YYYY-MM-DD HH:mm:ss',
                        hideDisabledOptions: true,
                        defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('23:59:59', 'HH:mm:ss')],
                      }"
                      :placeholder="[$t('startTime'), $t('endTime')]"
                      :value="defaultEffectiveTime"
                      @change="selectEffectiveTime"
                      @ok="()=>{$emit('search')}"
                    />
                  </a-form-model-item>
                </a-col>
              </a-row>
              <!-- 升级耗时 -->
              <a-row v-show="false">
                <a-col :md="24" :sm="24">
                  <a-form-model-item :label="$t('sjhs')" class="productionYearRow">
                    <a-row>
                      <a-col :md="11" :sm="24">
                        <a-input v-model="queryParams.vin" />
                      </a-col>
                      <a-col :md="2" :sm="24" class="joinLineCol">
                        <a-form-model-item :label="''" class="productionYearRow">
                          <span>——</span>
                        </a-form-model-item>
                      </a-col>
                      <a-col :md="11" :sm="24">
                        <a-input v-model="queryParams.vin" />
                      </a-col>
                    </a-row>
                  </a-form-model-item>
                </a-col>
              </a-row>
            </template>
          </filter-box-collection>
        </a-col>

        <a-col
          :xs="24"
          :sm="24"
          :md="24"
          :lg="24"
          :xl="24"
          :xxl="24">
          <div class="searchBtns">
            <a-button-group>
              <a-button
                type="primary"
                @click="handleSearch"
              >
                <i class="iconfont icon-chazhao"></i>
                {{ $t('inquiry') }}
              </a-button>
              <a-button @click="clearCondition">
                <i class="iconfont icon-qingkong"></i>
                {{ $t('clear') }}
              </a-button>
            </a-button-group>
            <a-button @click="exportList">
              <i class="iconfont icon-xiazai"></i>
              {{ $t('dccl') }}
            </a-button>
            <auth-button type="default" :auth="taskPerms[upgradeTriggerType.toLowerCase()].addcar" @click="exaddAction('addcar')" :disabled="taskInfo.channel === 0 || taskStatus!==12">
              <a-icon type="plus" />
              {{ $t('additionalcar') }}
            </auth-button>
            <auth-button type="default" :auth="taskPerms[upgradeTriggerType.toLowerCase()].batchdeletecar" @click="exaddAction('delete')" :disabled="taskInfo.channel === 0 || isUseBatchDelete">
              <a-icon type="delete" />
              {{ $t('multiDel') }}
            </auth-button>
            <!--<a-button @click="exaddAction('addcar')">-->
              <!--<a-icon type="plus" />-->
              <!--追加车辆-->
            <!--</a-button>-->
            <!--<a-button @click="exaddAction('delete')" :disabled="isUseBatchDelete">-->
              <!--<a-icon type="delete" />-->
              <!--批量删除-->
            <!--</a-button>-->
            <a-button
              @click="resendCommand"
              :loading="resending"
              v-if=" type === 2 && upgradeTriggerType !== 'warehouse'"
              :disabled="taskInfo.channel === 0 || !(taskStatus===12||resending)">
              {{ $t('resendCommand') }}
            </a-button>
          </div>
        </a-col>
      </a-row>
    </div>
  </div>
</template>
<script>
import FilterBoxCollection from '@/components/SelfComponents/FilterBoxCollection'
import CarModelSelect from '@/views/components/CarModelSelect.vue'
import PartSoftSelect from '@/views/components/PartSoftSelect'
import TaskSelect from '@/views/components/TaskSelect'
import OperationMenu from '@/components/OperationMenu'
import { downloadBlobFile } from '@/utils/functions'
import { mapState } from 'vuex'
import moment from 'moment'
import AuthButton from '@/components/AuthButton'
import { taskPerms  } from '@/config/permission'

const initQueryParams = {
  // vin: '',
  // modelIds: '',
  // 开始时间选择范围
  startTime: '',
  // 状态更新时间选择范围
  updateTime: '',
  importBatch: '',
  importTime: '',
  // 预约时间范围选择
  effectiveTime: ''
}
export default {
  components: {
    FilterBoxCollection,
    CarModelSelect,
    PartSoftSelect,
    TaskSelect,
    OperationMenu,
    AuthButton
  },
  props: {
    queryParams: {
      type: Object,
      default: () => {
        return {}
      }
    },
    taskId: {
      type: String,
      default: ''
    },
    // 1用户升级 2自动升级
    type: {
      type: Number,
      default: 1
    },
    isUseBatchDelete:{
      type:Boolean,
      default:true
    },
    upgradeTriggerType: {
      type: String,
      default: ''
    }
  },
  computed: {
    ...mapState({
      operationStatus: (state) => state.task.operationStatus
    }),
    defaultStartTime () {

      // eslint-disable-next-line max-len
      return [this.queryParams.startTimeGe ? moment(this.queryParams.startTimeGe) : null, this.queryParams.startTimeLe ? moment(this.queryParams.startTimeLe) : null]
    },
    defaultImportTime () {

      // eslint-disable-next-line max-len
      return [this.queryParams.importTimeGe ? moment(this.queryParams.importTimeGe) : null, this.queryParams.importTimeLe ? moment(this.queryParams.importTimeLe) : null]
    },
    defaultUpdateTime () {
      // eslint-disable-next-line max-len
      return [this.queryParams.updateTimeGe ? moment(this.queryParams.updateTimeGe) : null, this.queryParams.updateTimeLe ? moment(this.queryParams.updateTimeLe) : null]
    },
    defaultEffectiveTime () {
      // eslint-disable-next-line max-len
      return [this.queryParams.taskVehicleAppointTimeGe ? moment(this.queryParams.taskVehicleAppointTimeGe) : null, this.queryParams.taskVehicleAppointTimeLe ? moment(this.queryParams.taskVehicleAppointTimeLe) : null]
    },
    taskVehicleStatusOptions () {
      // 用户升级时没有唤醒中状态
      // eslint-disable-next-line max-len
      return this.type === 1 ? this.$store.state.dict.taskVehicleStatusDictCode.filter(item => item.value !== '11') : this.$store.state.dict.taskVehicleStatusDictCode
    },
    taskUpdateObjText () {
      return this.$store.getters.getDictCodeObj('taskUpdateDictCode')
    },
    exRowMenus () {
      return [
        {
          title: this.$t('dccl'),
          icon: 'icon-xiazai',
          key: 'dccl'
        },
        {
           title: this.$t('addcar'),
           icon: 'icon-xinjian1',
           key: 'addcar'
        }
      ]
    }
  },
  data () {
    return {
      taskPerms,
      queryParamsDesc: { ...initQueryParams },
      selectObj: {
        modelIds: {
          fetch: 'getModelName',
          data: null
        }
      },
      taskStatus: -1,
      taskInfo: {},
      resending: false,
      moment
    }
  },
  watch: {
    'queryParams.vin': {
      handler (val) {
        if (val) {
          return
        }
        this.queryParamsDesc.vin = ''
      }
    },
    'queryParams.importBatch': {
        handler (val) {
          if (val) {
            return
          }
          this.queryParamsDesc.importBatch = ''
        }
      },
    // 条件清空时显示搜索框中也能对应清除掉,车型
    'queryParams.modelIds': {
      handler (val) {
        if (val) {
          return
        }
        this.queryParamsDesc.modelIds = ''
      }
    },
    // 开始时间最小值
    'queryParams.startTimeGe': {
      handler (val) {
        if (val) {
          return
        }
        this.queryParamsDesc.startTime = ''
      }
    },
    // 预约时间最小值
    'queryParams.taskVehicleAppointTimeGe': {
      handler (val) {
        if (val) {
          return
        }
        this.queryParamsDesc.effectiveTime = ''
      }
    },
    // 更新时间最小值
    'queryParams.updateTimeGe': {
      handler (val) {
        if (val) {
          return
        }
        this.queryParamsDesc.updateTime = ''
      }
    },
    // 导入时间最小值
    'queryParams.importTimeGe': {
      handler (val) {
        if (val) {
          return
        }
        this.queryParamsDesc.importTime = ''
      }
    },
    taskId() {
      this.getTaskStatus()
    }
  },
  created () {
    this.getPageDictData()
    this.getTaskStatus()
  },
  updated () {
    // this.getTaskStatus()
  },
  methods: {
    // 获取任务状态
    getTaskStatus () {
      const vm = this
      vm.$api.getTaskInfor({ id: vm.taskId }).then((res) => {
        vm.taskStatus = res.data.status
        vm.taskInfo = res.data
      })
    },
    // 导出车辆
    exportList () {
      const vm = this
      const JnqueryParam = JSON.parse(JSON.stringify(vm.queryParams))
      // eslint-disable-next-line no-restricted-syntax
      for (const key in JnqueryParam) {
        if (JnqueryParam[key] === '') {
          JnqueryParam[key] = undefined
        }
      }
      JnqueryParam.taskId = vm.taskId
      vm.$api.exportTaskCars(JnqueryParam).then(res => {
        // 获取响应文件流
        // const blob = Response
        // const reader = new FileReader()
        // reader.readAsDataURL(blob) // 转换为base64，可以直接放入a表情href
        // reader.onload = function (e) {
        //   vm.$commonFun.fileDownLoad(e.target.result, `${vm.$t('executiveInformation')}.xlsx`)
        // }
        downloadBlobFile(res, this.$t('executiveInformation') + '.xlsx')
      })
    },
    // 重发指令
    resendCommand () {
      const vm = this
      this.$confirm({
        title: vm.$t('resendCommand'),
        content: vm.$t('resendCommandTip'),
        class: 'confirmStyle',
        width: 378,
        onOk () {
          vm.resending = true
          const queryParam = {
            taskId: vm.taskId
          }
          vm.$api.resendCommandTask(queryParam).then(() => {
            vm.$emit('search')
            vm.$message.success(vm.$t('successfullyOperation'))
          }).finally(() => {
            vm.resending = false
          })
        },
        onCancel () { }
      })
    },
    exaddAction (key) {
      if (key === 'dccl') {
        // 导出车辆
        this.exportList()
      } else if (key === 'addcar') {
        // 添加车辆
        this.$emit('showAddCar', true)
      } else if(key === 'delete') {
        // 批量删除
        this.$emit('batchDelete', true)
      }
    },
    handleSearch () {
      this.$emit('search')
    },
    changeOption (val, key) {

      if (typeof this.queryParamsDesc[key] !== 'undefined') {
        this.queryParamsDesc[key] = this[this.selectObj[key].fetch](val)
      }
      this.queryParams[key] = val
    },
    clearCondition () {
      this.$emit('clear')
    },
    // 删除搜索框中已选择的条件
    removeQueryKey (key) {
      if (typeof this.queryParams[key] === 'undefined') {
        this['remove' + key + 'Query']()
      } else {
        this.queryParams[key] = initQueryParams[key]
        this.queryParamsDesc[key] = ''
      }
      console.log(this.queryParams, 'queryParams')
    },
    // 获取车型名称
    getModelName (val) {
      if (this.selectObj.modelIds.data === null) {
        this.selectObj.modelIds.data = this.transfterArrayToObj(this.$refs.carModelSelect.modelOptions, 'id', 'name')
      }
      return this.selectObj.modelIds.data[val] || ''
    },
    // 选择开始日期(最小，最大)
    selectStartTime (date) {
      const result = this.setDateRangeDesc(date)
      this.queryParams.startTimeGe = result.minDate
      this.queryParams.startTimeLe = result.maxDate
      this.queryParamsDesc.startTime = result.desc ? this.$t('startTime') + '：' + result.desc : ''
    },
    // 选择预约时间(最小，最大)
    selectEffectiveTime (date, dateString) {
      const result = this.setDateRangeDesc(date)
      this.queryParams.taskVehicleAppointTimeGe = dateString[0]
      this.queryParams.taskVehicleAppointTimeLe = dateString[1]
      this.queryParamsDesc.effectiveTime = result.desc ? '预约时间' + '：' + result.desc : ''
    },
    selectImportTime (date) {

      const result = this.setDateRangeDesc(date)
      this.queryParams.importTimeGe = result.minDate
      this.queryParams.importTimeLe = result.maxDate
      this.queryParamsDesc.importTime = result.desc ? '导入时间' + '：' + result.desc : ''
    },
    // 处理选择日期范围(得到最小值，最大值，回显框显示结果)
    setDateRangeDesc (date) {

      let minDate = ''
      let maxDate = ''
      let desc = ''
      if (date.length) {
        minDate = this.$commonFun.getDateStr(date[0])
        maxDate = this.$commonFun.getDateStr(date[1])
        if (minDate === maxDate) {
          desc = minDate
        } else {
          desc = minDate + '~' + maxDate
        }
      }
      return { minDate, maxDate, desc }
    },
    // 选择更新日期(最小，最大)
    selectUpdateTime (date) {
      const result = this.setDateRangeDesc(date)
      this.queryParams.updateTimeGe = result.minDate
      this.queryParams.updateTimeLe = result.maxDate
      this.queryParamsDesc.updateTime = result.desc ? this.$t('ztgsTime') + '：' + result.desc : ''
    },
    inputVin(e){
      this.queryParamsDesc.vin = 'VIN:' + this.queryParams.vin
    },
    inputImportBatch(e){
      this.queryParamsDesc.importBatch = '导入车辆批次号:' + this.queryParams.importBatch

    },
    // 移除开始日期
    removestartTimeQuery () {
      this.queryParams.startTimeGe = null
      this.queryParams.startTimeLe = null
    },
    // 移除更新日期
    removeupdateTimeQuery () {
      this.queryParams.updateTimeGe = null
      this.queryParams.updateTimeLe = null
    },
    // 移除更新日期
    removeimportTimeQuery () {

      this.queryParams.importTimeGe = null
      this.queryParams.importTimeLe = null
    },
    // 移除预约时间
    removeeffectiveTimeQuery () {
      this.queryParams.taskVehicleAppointTimeGe = null
      this.queryParams.taskVehicleAppointTimeLe = null
    },
    transfterArrayToObj (arr, id, value) {
      const obj = {}
      arr.forEach(item => {
        obj[item[id]] = item[value]
      })
      return obj
    },
    getPageDictData () {
      ['getTaskVehicleStatusDictCodeData'].forEach(method => {
        this.$store.dispatch(method)
      })
    }
  }
}
</script>
<style lang="less">
.CarModelSearchWrap {
  .productionYearRow {
    .ant-form-item-control {
      .ant-calendar-picker {
        width: 100%;
      }
      .ant-calendar-range {
        width: 100%;
      }
    }
  }
  .alterView {
    min-width: 15px;
    padding: 0 10px;
    > i {
      font-size: 20px;
    }
  }
  .joinLineCol {
    // display: flex;
    // align-items: center;
    // justify-content: center;
    // background-color: red;
    text-align: center;
  }
}
</style>
